import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';

// 定义账户的类型
interface Account {
  id: string;
  name: string;
  balance: number;
}

// 定义初始状态的类型
interface AccountState {
  accounts: Account[];
  loading: boolean;
  error: string | null;
}

// 定义初始状态
const initialState: AccountState = {
  accounts: [],
  loading: false,
  error: null,
};

// 定义 API URL 常量
const API_URL = '/api/accounts';

// 定义异步 action
export const fetchAccounts = createAsyncThunk<Account[], void>(
  'account/fetchAccounts',
  async () => {
    const response = await axios.get(API_URL);
    return response.data.accounts; // 返回账户列表
  }
);

// 创建 slice
const accountSlice = createSlice({
  name: 'account',
  initialState,
  reducers: {
    setLoading(state, action: PayloadAction<boolean>) {
      state.loading = action.payload;
    },
    setAccounts(state, action: PayloadAction<Account[]>) {
      state.accounts = action.payload;
    },
    setError(state, action: PayloadAction<string | null>) {
      state.error = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchAccounts.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchAccounts.fulfilled, (state, action: PayloadAction<Account[]>) => {
        state.accounts = action.payload;
        state.loading = false;
      })
      .addCase(fetchAccounts.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取账户信息失败'; // 提供默认错误信息
      });
  },
});

// 导出 actions
export const { setLoading, setAccounts, setError } = accountSlice.actions;

// 导出选择器函数
export const selectAccounts = (state: { account: AccountState }) => state.account.accounts;
export const selectLoading = (state: { account: AccountState }) => state.account.loading;
export const selectError = (state: { account: AccountState }) => state.account.error;

// 导出 reducer
export default accountSlice.reducer;
